# SVN FILE: $Id$
#
# Project Name : PARASHARPLUS
#
# @package EmailNotifier.
# @author $Author$
# @copyright $Copyright:(c) 2008 PERSISTENT SYSTEMS LTD.All Rights Reserved$
# @version $Revision$
# @lastrevision $Date$
# @modifiedby $LastChangedBy$
# @lastmodified $LastChangedDate$
# @filesource $URL$
#

  require 'rubygems'
  require 'yaml'
  require 'net/smtp'
  require 'erb'
  require 'tempfile'
  require "#{File.dirname(__FILE__)}" + "/client_exception"

  # An helper class which helps to send email notification on any raised exception. 
  # Uses Ruby's built in Free SMTP library.
  class EmailNotifier
    
    # * Description*
    # * Create a instance of EmailNotifier
    # * Parameters*
    # * log: refernce to logger instance
    # * Returns*
    # * reference to Email Notifier instance
    # * Exception Raises*
    # * None  
    def initialize(log)
      @log = log
    end
    
    # * Description*
    # * The method to send  email notification
    # * Parameters*
    # * host: Host of the mail server
    # * port: port for sending email
    # * username: valid username for authentication
    # * password: valid password for authencation
    # * domain: domain name
    # * Returns*
    # * None
    # * Exception Raises*
    # * None  
    def send_email_msg(host, port, domain, username, password, from, to, error_message)
          Net::SMTP.start(host, port, domain, username, password, :login) do |smtp|
          smtp.send_message error_message, from, [to]
    end
  end

    # * Description*
    # * The method to create a message format for email
    # * Parameters*
    # * from: email address of the user from which email notification is been sent.
    # * to: destination email addresss.
    # * subject: Subject for the email
    # * message: Message body of the email
    # * Returns*
    # * None
    # * Exception Raises*
    # * None  
  def create_formatted_message(from, to, subject, message)
      formattedMessage = <<END_OF_MESSAGE
From: #{from}
To: #{to.join(";")}
Subject: #{subject}

#{message}
END_OF_MESSAGE
      return formattedMessage
  end
  
    # * Description*
    # * This method reads smtp configuration from the smpt_settings.yml file.
    # * Parameters*
    # * path: path to the smpt_settings.yml file.
    # * Returns*
    # * None
    # * Exception Raises*
    # * PropertyNotFoundException
  def read_smtp_configuration(smtp_settings_path)
    begin
          smtp_configuration = YAML::load(File.read(smtp_settings_path))
          smtp_settings = smtp_configuration["smtp_settings"]
          raise PropertyNotFoundException,'smtp_settings Entry missing in smtp_settings config file' if (smtp_settings.nil? || smtp_settings.eql?(""))          
          host = smtp_settings["host"]
          raise PropertyNotFoundException,'host Entry missing in smtp_settings config file' if  (host.nil? || host.eql?(""))          
          port = smtp_settings["port"]
          raise PropertyNotFoundException,'port Entry missing in smtp_settings config file' if  (port.nil? || port.eql?(""))          
          domain = smtp_settings["domain"]
          raise PropertyNotFoundException,'domain Entry missing in smtp_settings config file' if  (domain.nil? || domain.eql?(""))          
          username = smtp_settings["username"]
          raise PropertyNotFoundException,'username Entry missing in smtp_settings config file' if  (username.nil? || username.eql?(""))         
          password = smtp_settings["password"]
          raise PropertyNotFoundException,'password Entry missing in smtp_settings config file' if (password.nil? || password.eql?(""))          
          from = smtp_settings["from"]
          raise PropertyNotFoundException,'from Entry missing in smtp_settings config file' if (from.nil? || from.eql?(""))          
          to = smtp_settings["to"]
          raise PropertyNotFoundException,'to Entry missing in smtp_settings config file' if (to.nil? || to.eql?(""))
          to = to.split(";")
          
          sendmail_settings = smtp_configuration["sendmail_settings"]
          raise PropertyNotFoundException,'sendmail_settings Entry missing in smtp_settings config file' if (sendmail_settings.nil? || sendmail_settings.eql?(""))          
          from = sendmail_settings["from"]
          raise PropertyNotFoundException,'from Entry missing in smtp_settings config file' if (from.nil? || from.eql?(""))          
          to = sendmail_settings["to"]
          raise PropertyNotFoundException,'to Entry missing in smtp_settings config file' if (to.nil? || to.eql?(""))  

          gmail_settings = smtp_configuration["gmail_settings"]
          raise PropertyNotFoundException,'gmail_settings Entry missing in smtp_settings config file' if (gmail_settings.nil? || gmail_settings.eql?(""))          
          host = gmail_settings["host"]
          raise PropertyNotFoundException,'host Entry missing in smtp_settings config file' if  (host.nil? || host.eql?(""))          
          port = gmail_settings["port"]
          raise PropertyNotFoundException,'port Entry missing in smtp_settings config file' if  (port.nil? || port.eql?(""))          
          domain = gmail_settings["domain"]
          raise PropertyNotFoundException,'domain Entry missing in smtp_settings config file' if  (domain.nil? || domain.eql?(""))          
          username = gmail_settings["username"]
          raise PropertyNotFoundException,'username Entry missing in smtp_settings config file' if  (username.nil? || username.eql?(""))         
          password = gmail_settings["password"]
          raise PropertyNotFoundException,'password Entry missing in smtp_settings config file' if (password.nil? || password.eql?(""))          
          from = gmail_settings["from"]
          raise PropertyNotFoundException,'from Entry missing in smtp_settings config file' if (from.nil? || from.eql?(""))          
          to = gmail_settings["to"]
          raise PropertyNotFoundException,'to Entry missing in smtp_settings config file' if (to.nil? || to.eql?(""))
          to = to.split(";")
          
      rescue PropertyNotFoundException => pnf
          puts "Error message while reading smtp_settings.yml file"
          puts "#{pnf.class} - #{pnf.message}"
          Process.exit
      rescue Exception => e
          puts "Error message while reading smtp_settings.yml file"
          puts "#{e.class} - #{e.message}"
          Process.exit
      end
      smtp_configuration
  end

    # * Description*
    # * This method sends mails using built-in sendmail tool
    # * Parameters*
    # * from: email address of the sender.
    # * to:  email address of the recepient
    # * subject: email subject    
    # * body: Message body
    # * Returns*
    # * None
    # * Exception Raises*
    # * Exception
  def sendmail(from, to, subject, body)
        begin     
           filename = "#{File.dirname(__FILE__)}" + "/email_headers.erb"
           email_headers = result = tmp_file = nil
           File.open(filename) do |f|
              erb = ERB.new(f.read)
              result = erb.result(binding)
           end
           email_headers = result.split("\r\n"); 
           tmp_file = Tempfile.new("tempfile")
           email_headers.each do |header|
             tmp_file << header + "\r\n"
           end
           tmp_file.rewind
           execute_cmd =  "#{`sendmail -t <  #{tmp_file.path}`}"
        rescue Exception => e
           @log.info("#{e.class}: #{e.message}") if @log
        ensure 
          tmp_file.close(true)
        end    
  end 
end
